import { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";

// 路由鉴权
const AuthRouter = (props: any) => {
	const token = localStorage.getItem("token");
	const navigate = useNavigate();
	const { pathname } = useLocation();

	useEffect(() => {
		if (token) {
			// 已经登录了，但是你通过浏览器里直接访问login的话不允许直接跳转到login路由，必须通过logout来控制退出登录或者是token过期返回登录界面
			if (location.pathname == "/" || location.pathname == "/login") {
				navigate("/home/index");
			} else {
				// 如果是其他路由就跳到其他的路由
				navigate(pathname);
			}
		} else {
			navigate("/login");
		}
	}, [token, pathname]);

	return props.children;
};
export default AuthRouter;
